package com.usian.skill.mq;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.GoodsService;
import com.usian.skill.service.SkillOrderService;
import com.usian.skill.service.SkillService;
import com.usian.skill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MQReceiver {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SkillOrderService skillOrderService;
    @Autowired
    private SkillService skillService;

    @RabbitListener(queues = MQConfig.QUEUE)
    public void receiver(String message){
        log.info("receiver message:"+message);
    }
    @RabbitListener(queues = MQConfig.SkillQUEUE)
    public void receiverSkill(String message){
        SkillMessage skillMessage = JSON.parseObject(message, SkillMessage.class);
        GoodsVo goodsVo = goodsService.getGoodsIdDB(skillMessage.getGoodsId());
        if(goodsVo.getStockCount()<=0){
            return;
        }
        //判定是否秒杀到
        SkillOrder order = skillOrderService.getOne(Wrappers.<SkillOrder>lambdaQuery().eq(SkillOrder::getGoodsId, skillMessage.getGoodsId()).eq(SkillOrder::getUserId,skillMessage.getUserId()));
        if(order!=null){
            return;
        }
        //减库存，生成订单
        skillService.skill(skillMessage.getUserId(),goodsVo);
        log.info("receiver message:"+message);
    }
}
